<script lang="ts" setup>
import { ref, h, onMounted } from "vue"
import {
  NDataTable,
  NInput,
  NButton,
  NModal,
  useMessage,
  useDialog,
  NForm,
  NFormItem,
  type DataTableColumns,
} from "naive-ui"
import { isPC } from "@/hooks/resize"
import { useAdminSettingStore } from "@/stores/admin/setting"
import {
  getScoreList,
  type getScoreList_Item,
  updateScore,
  deleteScore,
  addScore,
} from "@api/index"
import partLoading from "@/utilComponents/loading/partLoading/index.vue"

const pagination = ref({
  pageSize: 10,
  pageCount: 2,
  page: 1,
})
const paginationCurrentPageInit = () => {
  pagination.value.page = 1
}
const settingStore = useAdminSettingStore()
const dialog = useDialog()
const message = useMessage()
const classifyBox = ref<null | HTMLElement>(null)
const tableMaxHeight = ref<string>("")

const data = ref<Array<getScoreList_Item>>([])

const filterPayload = ref<{
  stuId: string
  stuName: string
}>({
  stuId: "",
  stuName: "",
})

const formPayload = ref<Omit<getScoreList_Item, "isDelete">>({
  stuId: "",
  stuName: "",
  english: "",
  chemistry: "",
  chinese: "",
  organism: "",
  mathematics: "",
  physics: "",
})

const formPayloadInit = () => {
  formPayload.value = {
    stuId: "",
    stuName: "",
    english: "",
    chemistry: "",
    chinese: "",
    organism: "",
    mathematics: "",
    physics: "",
  }
}

const rules = {
  stuName: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入姓名",
  },
  stuId: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入学号",
  },
  english: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入英语成绩",
  },
  chemistry: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入化学成绩",
  },
  chinese: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入英语成绩",
  },
  organism: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入生物成绩",
  },
  mathematics: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入数学成绩",
  },
  physics: {
    required: true,
    trigger: ["blur", "input"],
    message: "请输入物理成绩",
  },
}
const dataTableIsLoading = ref<boolean>(true)
const getData = async () => {
  dataTableIsLoading.value = true
  const res = await getScoreList({
    pageNum: pagination.value.page,
    pageSize: pagination.value.pageSize,
    ...filterPayload.value,
    isDelete: 0,
  })
  console.log("data=", res)
  const timerId = setTimeout(() => {
    dataTableIsLoading.value = false
    pagination.value.pageCount = res.data.totalPage
    data.value = res.data.list
    clearTimeout(timerId)
  }, 500)
}
onMounted(() => {
  initTableMaxHeight()
  getData()
})

const updatePage = async (currentPage: number) => {
  pagination.value.page = currentPage
  await getData()
}
const initTableMaxHeight = () => {
  tableMaxHeight.value = classifyBox.value.offsetHeight - 170 + ""
}

const showModal = ref<boolean>(false)
const btnLoading = ref<boolean>(false)
const btnDisabled = ref<boolean>(false)

const formRef = ref(null)
const EditStudentInfoMode = ref<number>(0)
const openEditStudentInfoModal = (mode: number, data?: Omit<getScoreList_Item, "isDelete">) => {
  if (mode == 1) {
    formPayload.value = data
    console.log("formPayload=", formPayload.value)
  } else {
    formPayloadInit()
  }
  EditStudentInfoMode.value = mode
  showModal.value = true
}

const confirm = () => {
  formRef.value?.validate(async errors => {
    if (!errors) {
      message.success("验证成功")
      btnLoading.value = true
      btnDisabled.value = true
      if (EditStudentInfoMode.value == 0) {
        //新增模式
        createStudent()
      } else {
        //更新模式
        modifyStudent()
      }
    } else {
      console.log(errors)
      message.error("验证失败")
    }
  })
}

const modifyStudent = async () => {
  const res = await updateScore(formPayload.value)
  console.log("createStudent", res)

  if (res.status == 200) {
    setTimeout(() => {
      showModal.value = false
      btnLoading.value = false
      btnDisabled.value = false
      paginationCurrentPageInit()
      getData()
      message.success("更新成绩信息成功")
    }, 1000)
  } else {
    btnLoading.value = false
    btnDisabled.value = false
    message.error("更新成绩信息失败")
  }
}

const createStudent = async () => {
  const res = await addScore(formPayload.value)
  console.log("createStudent", res)

  if (res.status == 200) {
    setTimeout(() => {
      showModal.value = false
      btnLoading.value = false
      btnDisabled.value = false
      paginationCurrentPageInit()
      getData()
      message.success("新增成绩成功")
    }, 1000)
  } else {
    btnLoading.value = false
    btnDisabled.value = false
    message.error("新增成绩失败")
  }
}

const clearFilterData = () => {
  filterPayload.value = {
    stuId: "",
    stuName: "",
  }
  getData()
}
const headers: DataTableColumns<getScoreList_Item> = [
  {
    title: "学号",
    key: "stuId",
    align: "center",
  },
  {
    title: "姓名",
    key: "stuName",
    align: "center",
  },
  {
    title: "语文",
    key: "chinese",
    align: "center",
  },
  {
    title: "数学",
    key: "mathematics",
    align: "center",
  },
  {
    title: "英语",
    key: "english",
    align: "center",
  },
  {
    title: "物理",
    key: "physics",
    align: "center",
  },
  {
    title: "生物",
    key: "organism",
    align: "center",
  },
  {
    title: "化学",
    key: "chemistry",
    align: "center",
  },
  {
    title: "Action",
    key: "Action",
    align: "center",
    width: 200,
    fixed: "right",
    render(row, index) {
      const DeleteStudent = () => {
        dialog.error({
          title: "是否删除此条数据",
          positiveText: "是",
          negativeText: "算了",
          onPositiveClick: async () => {
            const res = await deleteScore(row.id)
            if (res.status == 200) {
              message.success("成绩删除成功")
              paginationCurrentPageInit()
              getData()
            } else {
              message.error("成绩删除失败")
            }
          },
        })
      }

      return h(
        "div",
        {
          class: "action",
        },
        {
          default() {
            return [
              h(
                NButton,
                {
                  onClick: DeleteStudent,
                  type: "error",
                  style: `margin-right:20px;margin-bottom:${isPC.value ? "0" : "10px"}`,
                },
                {
                  default() {
                    return "Delete"
                  },
                }
              ),
              h(
                NButton,
                {
                  onClick: () => {
                    openEditStudentInfoModal(1, row)
                  },
                  type: "primary",
                },
                {
                  default() {
                    return "Edit"
                  },
                }
              ),
            ]
          },
        }
      )
    },
  },
]

// const handleUpdateSex = v => {
//   filterPayload.value.sex = v
// }
</script>
<template>
  <div
    class="classifyBox"
    ref="classifyBox"
    :style="{
      background: settingStore.theme == 'light' ? '#fff' : '#333',
    }"
  >
    <div class="header">
      <n-button type="primary" @click="openEditStudentInfoModal(0)">+ New</n-button>
      <div class="search">
        <div class="title">姓名：</div>
        <div class="input">
          <n-input
            v-model:value="filterPayload.stuName"
            type="text"
            placeholder="请输入姓名以供筛选"
          />
        </div>
      </div>
      <div class="search">
        <div class="title">学号：</div>
        <div class="input">
          <n-input
            v-model:value="filterPayload.stuId"
            type="text"
            placeholder="请输入学号以供筛选"
          />
        </div>
      </div>
      <n-button type="primary" @click="getData">查询</n-button>
      <n-button type="primary" @click="clearFilterData">重置</n-button>
    </div>
    <n-data-table
      :columns="headers"
      :data="data"
      :pagination="pagination"
      :row-key="row => row.id"
      striped
      :max-height="tableMaxHeight"
      :loading="dataTableIsLoading"
      :remote="true"
      @update:page="updatePage"
    >
      <template v-slot:loading>
        <partLoading :isShow="dataTableIsLoading" auto text="Loading" />
      </template>
    </n-data-table>

    <n-modal v-model:show="showModal">
      <div class="modal-content" v-drag="true">
        <header id="trigge">Edit Student Score Info</header>
        <div class="form">
          <n-form
            ref="formRef"
            :model="formPayload"
            :rules="rules"
            label-placement="left"
            label-width="auto"
            require-mark-placement="right-hanging"
            size="medium"
          >
            <n-form-item label="姓名" path="stuName">
              <n-input v-model:value="formPayload.stuName" placeholder="请输入姓名" />
            </n-form-item>

            <n-form-item label="学号" path="stuId">
              <n-input v-model:value="formPayload.stuId" placeholder="请输入学号" />
            </n-form-item>

            <n-form-item label="语文" path="chinese">
              <n-input v-model:value="formPayload.chinese" placeholder="请输入语文成绩" />
            </n-form-item>

            <n-form-item label="数学" path="mathematics">
              <n-input v-model:value="formPayload.mathematics" placeholder="请输入数学成绩" />
            </n-form-item>

            <n-form-item label="英语" path="english">
              <n-input v-model:value="formPayload.english" placeholder="请输入英语成绩" />
            </n-form-item>

            <n-form-item label="物理" path="physics">
              <n-input v-model:value="formPayload.physics" placeholder="请输入物理成绩" />
            </n-form-item>

            <n-form-item label="生物" path="organism">
              <n-input v-model:value="formPayload.organism" placeholder="请输入生物成绩" />
            </n-form-item>

            <n-form-item label="化学" path="chemistry">
              <n-input v-model:value="formPayload.chemistry" placeholder="请输入化学成绩" />
            </n-form-item>

            <div class="modalAction">
              <n-button type="error" @click="showModal = false">Cancel</n-button>
              <n-button
                type="primary"
                @click="confirm"
                :loading="btnLoading"
                :disabled="btnDisabled"
                >{{ btnDisabled ? "" : EditStudentInfoMode == 0 ? "Create" : "Update" }}</n-button
              >
            </div>
          </n-form>
        </div>
      </div>
    </n-modal>
  </div>
</template>
<style lang="scss" scoped>
.modalAction {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
}

:deep(.n-data-table-loading-wrapper) {
  width: 100%;
  height: 100%;
}

.modal-content {
  width: 500px;
  min-height: 500px;
  background-color: var(--BlockBgColor);
  border-radius: 10px;
  padding: 20px;
  padding-top: 0;
  position: relative;

  header {
    box-sizing: border-box;
    padding-top: 10px;
    width: 100%;
    font-size: 18px;
    color: #666;
    text-align: center;
    margin-bottom: 20px;
    user-select: none;
  }
}

.classifyBox {
  border-radius: var(--radius);
  background: var(--BlockBgColor);
  box-sizing: border-box;
  transition: background 0.3s var(--n-bezier);
  color: var(--TextColor);
  box-sizing: border-box;
  padding: 10px;

  .header {
    width: 100%;
    display: flex;
    align-items: center;
    gap: 30px;
    margin-bottom: 15px;

    .search {
      display: flex;
      align-items: center;

      .title {
      }

      .input {
      }
    }
  }
}
</style>
